package com.edu.app.service.impl.wechat;

import com.edu.app.model.wechat.WxError;
import com.edu.app.model.wechat.WxErrorException;
import com.edu.app.service.sys.wechat.WeChatServiceExecutor;
import com.edu.app.service.sys.wechat.WechatBaseService;
import com.edu.app.service.sys.wechat.WechatQRCodeService;
import com.edu.app.util.http.DataType;
import com.edu.app.util.json.JsonUtil;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

@Service
public class WechatQRCodeServiceImpl   implements WechatQRCodeService {

    String CREATE_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s";

    private final static String QR_SCENE = "QR_SCENE";
    private final static String QR_STR_SCENE = "QR_STR_SCENE";
    // 永久二维码  
    private final static String QR_LIMIT_SCENE = "QR_LIMIT_SCENE";
    // 永久二维码(字符串)  
    private final static String QR_LIMIT_STR_SCENE = "QR_LIMIT_STR_SCENE";

    WeChatServiceExecutor executor;
    WechatBaseService baseService;

    WechatQRCodeServiceImpl(WeChatServiceExecutor executor,WechatBaseService wechatBaseService){
        this.executor    = executor;
        this.baseService = wechatBaseService;
    }
        /**
     * 发送模板消息

     * @param sceneId
     * @return 状态
     */
    @Override
    public String qrCodeCreateTmpTicket(int sceneId, Integer expireSeconds) throws WxErrorException {

        TreeMap<String, Object> params = new TreeMap<String, Object>();
        String response = null;
        try  {
            Map<String,Integer> intMap = new HashMap<String,Integer>();
            intMap.put("scene_id",sceneId);
            Map<String,Map<String,Integer>> mapMap = new HashMap<String,Map<String,Integer>>();
            mapMap.put("scene", intMap);

            Map<String,Object> paramsMap = new HashMap<String,Object>();
            paramsMap.put("expire_seconds", expireSeconds);
            paramsMap.put("action_name", QR_SCENE);
            paramsMap.put("action_info", mapMap);

            String data = JsonUtil.toJson(paramsMap);


            params.put("content",data);
            response = executor.execute(CREATE_TICKET_URL,params,ExecutorType.POSTSYNC, DataType.JSON);
            //templateMsgResult = (TemplateMsgResult)JsonUtil.fromJson(response, TemplateMsgResult.class);
        } catch(WxErrorException e){
            throw e;
        }catch(JsonProcessingException e){
            e.printStackTrace();
        }


        return response;
    }

    @Override
    public String qrCodeCreateTmpTicket(String sceneStr, Integer expireSeconds) throws WxErrorException{

        TreeMap<String, Object> params = new TreeMap<String, Object>();
        String response = null;
        try  {
            Map<String,String> sceneStrMap = new HashMap<String,String>();
            sceneStrMap.put("scene_str",sceneStr);
            Map<String,Map<String,String>> sceneMap = new HashMap<String,Map<String,String>>();
            sceneMap.put("scene", sceneStrMap);

            Map<String,Object> paramsMap = new HashMap<String,Object>();
            paramsMap.put("expire_seconds", expireSeconds);
            paramsMap.put("action_name", QR_STR_SCENE);
            paramsMap.put("action_info", sceneMap);

            String data = JsonUtil.toJson(paramsMap);


            params.put("content",data);
            response = executor.execute(CREATE_TICKET_URL,params,ExecutorType.POSTSYNC,DataType.JSON);
            //templateMsgResult = (TemplateMsgResult)JsonUtil.fromJson(response, TemplateMsgResult.class);
        } catch(WxErrorException e){
            throw e;
        }catch(JsonProcessingException e){
            e.printStackTrace();
        }


        return response;
    }

    @Override
    public String qrCodeCreateLastTicket(int sceneId) throws WxErrorException{
        TreeMap<String, Object> params = new TreeMap<String, Object>();
        String response = null;
        try  {
            Map<String,Integer> intMap = new HashMap<String,Integer>();
            intMap.put("scene_id",sceneId);
            Map<String,Map<String,Integer>> mapMap = new HashMap<String,Map<String,Integer>>();
            mapMap.put("scene", intMap);

            Map<String,Object> paramsMap = new HashMap<String,Object>();

            paramsMap.put("action_name", QR_LIMIT_SCENE);
            paramsMap.put("action_info", mapMap);

            String data = JsonUtil.toJson(paramsMap);


            params.put("content",data);
            response =  executor.execute(CREATE_TICKET_URL,params,ExecutorType.POSTSYNC,DataType.JSON);
            //templateMsgResult = (TemplateMsgResult)JsonUtil.fromJson(response, TemplateMsgResult.class);
        } catch(WxErrorException e){
            throw e;
        }catch(JsonProcessingException e){
            e.printStackTrace();
        }


        return response;
    }

    @Override
    public String qrCodeCreateLastTicket(String sceneStr) throws WxErrorException{
        TreeMap<String, Object> params = new TreeMap<String, Object>();
        String response = null;
        try  {
            Map<String,String> sceneIdMap = new HashMap<String,String>();
            sceneIdMap.put("scene_str",sceneStr);
            Map<String,Map<String,String>> sceneMap = new HashMap<String,Map<String,String>>();
            sceneMap.put("scene", sceneIdMap);

            Map<String,Object> paramsMap = new HashMap<String,Object>();

            paramsMap.put("action_name", QR_LIMIT_STR_SCENE);
            paramsMap.put("action_info", sceneMap);

            String data = JsonUtil.toJson(paramsMap);


            params.put("content",data);
            response =  executor.execute(CREATE_TICKET_URL,params,ExecutorType.POSTSYNC,DataType.JSON);
            //templateMsgResult = (TemplateMsgResult)JsonUtil.fromJson(response, TemplateMsgResult.class);
        } catch(WxErrorException e){
            throw e;
        }catch(JsonProcessingException e){
            e.printStackTrace();
        }

        return response;
    }

    @Override
    public String qrCodePictureUrl(String ticket, boolean needShortUrl) throws WxErrorException{
        String url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s";
        try {
            String resultUrl = String.format(url,
                    URLEncoder.encode(ticket, StandardCharsets.UTF_8.name()));

            if (needShortUrl) {
                return  baseService.shortUrl(resultUrl);
            }

            return resultUrl;
        } catch (UnsupportedEncodingException e) {
            throw new WxErrorException(WxError.builder().errcode(-1).errmsg(e.getMessage()).build());
        }
    }

    @Override
    public String qrCodePictureUrl(String ticket) throws WxErrorException{
        return qrCodePictureUrl(ticket, false);
    }
}
